package cn.wink.springcloud.controller;

import cn.wink.springcloud.entites.Payment;
import cn.wink.springcloud.lb.LoadBalanced;
import cn.wink.springcloud.lb.LoadBalancedImpl;
import cn.wink.springcloud.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;

/**
 * @author xw
 * @date 2020-05-03 14:15
 */
@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {

    // private static final String PAYMENT_URL = "http://localhost:8001";
    private static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE";

    @Resource
    private RestTemplate restTemplate;

    /**
     * 服务发现：获得所有服务信息
     */
    @Resource
    private DiscoveryClient discoveryClient;


    @PostMapping("/create")
    public Result create(Payment payment) {
        return restTemplate.postForObject(PAYMENT_URL + "/payment/create", payment, Result.class);
    }

    @GetMapping("/get/{id}")
    public Result get(@PathVariable("id") Long id) {
        return restTemplate.getForObject(PAYMENT_URL + "/payment/get/" + id, Result.class);
    }

    @GetMapping("/get/lb/{id}")
    public Result getLB(@PathVariable("id") Long id) {
        LoadBalanced loadBalanced = LoadBalancedImpl.getOne(discoveryClient, "CLOUD-PAYMENT-SERVICE");
        ServiceInstance instances = loadBalanced.getInstances();
        URI uri = instances.getUri();
        return restTemplate.getForObject(uri + "/payment/get/" + id, Result.class);
    }

    // ====================> zipkin+sleuth
    @GetMapping("/consumer/payment/zipkin")
    public String paymentZipkin() {
        String result = restTemplate.getForObject("http://localhost:8001" + "/payment/zipkin/", String.class);
        return result;
    }
}
